package br.com.cnpv.modelo.dao;

import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;

import br.com.cnpv.modelo.acesso.idao.IVeiculoDAO;
import br.com.cnpv.modelo.entity.Associacao;
import br.com.cnpv.modelo.entity.Veiculo;
import br.com.cnpv.modelo.entity.VeiculoCliente;

public class VeiculoDAO implements IVeiculoDAO{

	@SuppressWarnings("unchecked")
	public List<Veiculo> buscar(Veiculo veiculo, Session session)
			throws HibernateException {
		
		String clausula = "";
		Query query = null;
		
		if(veiculo.getPlaca() != null && StringUtils.isNotEmpty(veiculo.getPlaca())){
			
			clausula = veiculo.getPlaca();			
			query = session.getNamedQuery("Veiculo.buscarByPlaca");
			query.setString("clausula", clausula);

		}else if(veiculo.getChassi() != null && StringUtils.isNotEmpty(veiculo.getChassi())){
			
			clausula = veiculo.getChassi();
			query = session.getNamedQuery("Veiculo.buscarByChassi");
			query.setString("clausula", clausula);
			
		} else if(veiculo.getVeiculoCliente()!=null) {
			
			clausula = veiculo.getVeiculoCliente().getCliente().getNome();
			query = session.getNamedQuery("Veiculo.buscarByCliente");
			query.setString("clausula", "%"+clausula+"%");
		}

		return query.list();
	}

	@Override
	public Veiculo saveOrUpdate(Veiculo veiculo, Session session)
			throws HibernateException {
		return (Veiculo) session.merge(veiculo);
	}
	
	@SuppressWarnings("unchecked")
	@Override
	public List<Veiculo> listar(Session session) throws HibernateException 
	{
		Query query = session.getNamedQuery("Veiculo.listar");
		return query.list();
	}
}